package org.sippr.rvt2ifc.utils;

import net.sourceforge.pinyin4j.PinyinHelper;
import net.sourceforge.pinyin4j.format.HanyuPinyinCaseType;
import net.sourceforge.pinyin4j.format.HanyuPinyinOutputFormat;
import net.sourceforge.pinyin4j.format.HanyuPinyinToneType;

public class PinYin {
    public static String convertToPinyin(String chinese) {
        HanyuPinyinOutputFormat format = new HanyuPinyinOutputFormat();
        format.setCaseType(HanyuPinyinCaseType.LOWERCASE); // 小写
        format.setToneType(HanyuPinyinToneType.WITHOUT_TONE); // 不带声调

        StringBuilder pinyin = new StringBuilder();

        for (char c : chinese.toCharArray()) {
            if (Character.isWhitespace(c)) {
                pinyin.append("_"); // 处理空格
            } else if (Character.isDigit(c) || !Character.isLetter(c) || c == '.') {
                pinyin.append(c); // 直接保留字母、数字和后缀名
            } else {
                try {
                    String[] pinyinArray = PinyinHelper.toHanyuPinyinStringArray(c, format);
                    if (pinyinArray != null) {
                        pinyin.append(pinyinArray[0]); // 取第一个拼音
                    } else {
                        pinyin.append(c); // 处理非汉字字符
                    }
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
        }

        return pinyin.toString();
    }
}
